package com.ming_za.odupdaterserver.core.service.account;

import com.ming_za.odupdaterserver.core.sqlite.domain.AdminAccount;
import com.ming_za.odupdaterserver.core.sqlite.domain.Res;
import com.ming_za.odupdaterserver.core.sqlite.mapper.AdminAccountMapper;
import com.ming_za.odupdaterserver.core.utils.cache.options.MapInternalCacheOptions;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class AccountCacheOptions extends MapInternalCacheOptions<Long, AdminAccount> {

    private final AdminAccountMapper adminAccountMapper;

    public AccountCacheOptions(AdminAccountMapper adminAccountMapper) {
        this.adminAccountMapper = adminAccountMapper;
    }

    @Override
    public AdminAccount getValue(Long account) {
        return adminAccountMapper.selectByPrimaryKey(account);
    }

    @Override
    public void putValue(Long key, AdminAccount value) {
        value.setAccount(key);
        adminAccountMapper.insert(value);
    }

    @Override
    public void replaceValue(Long key, AdminAccount value) {
        adminAccountMapper.updateByPrimaryKey(value);
    }

    @Override
    public void removeValue(Long account) {
        adminAccountMapper.deleteByPrimaryKey(account);
    }

    @Override
    public void clear() {

    }

    @Override
    public Map<Long, AdminAccount> newInstance() {
        return new HashMap<>();
    }

    @Override
    public Map<Long, AdminAccount> getData() {
        Map<Long, AdminAccount> data = new ConcurrentHashMap<>();
        List<AdminAccount> resList = adminAccountMapper.selectAll();
        for (AdminAccount account : resList) {
            data.put(account.getAccount(), account);
        }
        return data;
    }

    /**
     * @param data 数据
     * @deprecated 不建议同时设置所有账号数据
     */
    @Deprecated
    @Override
    public void setData(Map<Long, AdminAccount> data) {

    }
}
